const { HealthRecord, FamilyMember } = require('../models');
const { Op } = require('sequelize');
const moment = require('moment');

// 获取健康趋势数据
exports.getTrends = async (req, res) => {
  try {
    const userId = req.user.id;
    const { memberId, type, timeRange } = req.query;
    
    if (!memberId || !type) {
      return res.status(400).json({
        success: false,
        message: '缺少必要参数'
      });
    }
    
    // 验证成员是否属于当前用户
    const member = await FamilyMember.findOne({
      where: {
        id: memberId,
        user_id: userId
      }
    });
    
    if (!member) {
      return res.status(403).json({
        success: false,
        message: '无权查看此成员数据'
      });
    }
    
    // 根据时间范围确定查询时间
    let startDate;
    const endDate = moment().endOf('day').toDate();
    
    switch (timeRange) {
      case '7days':
        startDate = moment().subtract(7, 'days').startOf('day').toDate();
        break;
      case '30days':
        startDate = moment().subtract(30, 'days').startOf('day').toDate();
        break;
      case '3months':
        startDate = moment().subtract(3, 'months').startOf('day').toDate();
        break;
      case '6months':
        startDate = moment().subtract(6, 'months').startOf('day').toDate();
        break;
      case '1year':
        startDate = moment().subtract(1, 'year').startOf('day').toDate();
        break;
      default:
        startDate = moment().subtract(30, 'days').startOf('day').toDate();
    }
    
    // 查询记录
    const records = await HealthRecord.findAll({
      where: {
        member_id: memberId,
        type,
        record_time: {
          [Op.between]: [startDate, endDate]
        }
      },
      order: [['record_time', 'ASC']]
    });
    
    // 处理数据，按日期分组
    const trendData = {
      categories: [],
      series: [{
        name: type,
        data: []
      }]
    };
    
    // 如果记录不多，直接使用记录的日期和值
    if (records.length > 0) {
      records.forEach(record => {
        const dateStr = moment(record.record_time).format('MM-DD');
        trendData.categories.push(dateStr);
        
        // 根据记录类型处理数值
        let value;
        if (type === '血压' && record.raw_value && record.raw_value2) {
          // 血压特殊处理，使用收缩压
          value = record.raw_value;
        } else {
          value = record.raw_value;
        }
        
        trendData.series[0].data.push(value);
      });
    } else {
      // 如果没有记录，返回空数据
      trendData.categories = [];
      trendData.series[0].data = [];
    }
    
    return res.json({
      success: true,
      data: trendData
    });
  } catch (error) {
    console.error('获取健康趋势数据错误:', error);
    return res.status(500).json({
      success: false,
      message: '服务器错误'
    });
  }
}; 